package vip.xiaonuo.client.modular.wxpay.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.profitsharing.Receiver;
import com.github.binarywang.wxpay.bean.profitsharing.request.ProfitSharingQueryRequest;
import com.github.binarywang.wxpay.bean.profitsharing.request.ProfitSharingRequest;
import com.github.binarywang.wxpay.bean.profitsharing.result.ProfitSharingQueryResult;
import com.github.binarywang.wxpay.bean.profitsharing.result.ProfitSharingResult;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.modular.order.entity.BizFzOrder;
import vip.xiaonuo.biz.modular.order.entity.BizFzOrderDetail;
import vip.xiaonuo.biz.modular.order.entity.BizOrder;
import vip.xiaonuo.biz.modular.order.param.BizTicketOrderIdParam;
import vip.xiaonuo.biz.modular.order.service.BizTicketOrderService;
import vip.xiaonuo.biz.modular.ticket.entity.Ticket;
import vip.xiaonuo.biz.modular.ticket.service.TicketService;
import vip.xiaonuo.biz.modular.user.entity.BizFzUser;
import vip.xiaonuo.biz.modular.user.service.BizFzUserService;
import vip.xiaonuo.client.modular.wxpay.service.MyWxPayService;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 微信支付服务实现类
 *
 * @author SNOWY_TEAM
 */
@Slf4j
@Service
@EnableScheduling
public class MyWxPayServiceImpl implements MyWxPayService {

    @Resource
    private WxPayService wxPayService;

    @Resource
    private BizTicketOrderService bizTicketOrderService;

    @Resource
    private TicketService ticketService;

    @Resource
    private BizFzUserService bizFzUserService;

    @Autowired
    private RedissonClient redissonClient;

    @Value("${wx.pay.notifyUrl}")
    private String notifyUrl;

    @Value("${wx.pay.mchId}")
    private String mchId;

    @Resource
    private SysOrgService sysOrgService;



    /**
     * 请求单次分账
     *
     * @param orderId   订单ID
     * @param outOrderNo 分账单号
     * @param receivers 分账接收方列表
     * @return 分账结果
     */
    public Map<String, Object> profitSharing(String orderId, String outOrderNo, List<Map<String, Object>> receivers) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            // 获取订单信息
            BizTicketOrderIdParam param = new BizTicketOrderIdParam();
            param.setId(orderId);
            BizOrder order = bizTicketOrderService.detail(param);

            if (order == null) {
                throw new CommonException("订单不存在");
            }

            if (!"已完成".equals(order.getStatus()) && !"已支付".equals(order.getStatus())) {
                throw new CommonException("只有已支付或已完成的订单才能进行分账");
            }

            // 检查微信订单号是否存在
            if (StrUtil.isBlank(order.getWxOrderId())) {
                throw new CommonException("订单缺少微信支付订单号");
            }

            try {
                // 准备分账请求参数
                Map<String, Object> requestParams = new HashMap<>();
                requestParams.put("appid", wxPayService.getConfig().getAppId());
                requestParams.put("transaction_id", order.getWxOrderId());
                requestParams.put("out_order_no", outOrderNo);

                // 构建分账接收方列表
                List<Map<String, Object>> receiversList = new ArrayList<>();

                for (Map<String, Object> receiver : receivers) {
                    String type = (String) receiver.get("type");
                    String account = (String) receiver.get("account");
                    int amount = (Integer) receiver.get("amount");
                    String description = (String) receiver.get("description");

                    // 验证必要字段
                    if (StrUtil.isBlank(type) || StrUtil.isBlank(account) || amount <= 0 || StrUtil.isBlank(description)) {
                        throw new CommonException("分账接收方信息不完整");
                    }

                    Map<String, Object> receiverMap = new HashMap<>();
                    receiverMap.put("type", type);
                    receiverMap.put("account", account);
                    receiverMap.put("amount", amount);
                    receiverMap.put("description", description);
                    receiversList.add(receiverMap);
                }

                requestParams.put("receivers", receiversList);
                // 设置是否解冻剩余未分资金
                requestParams.put("unfreeze_unsplit", true);

                String requestJson = JSONUtil.toJsonStr(requestParams);
                log.info("分账请求参数: {}", requestJson);

                // 调用微信支付V3 API
                String url = String.format("%s/v3/profitsharing/orders","https://api.mch.weixin.qq.com");

                String responseStr = wxPayService.postV3(url, requestJson);
                log.info("分账结果: {}", responseStr);

                // 解析响应结果
                Map<String, Object> responseMap = JSONUtil.toBean(responseStr, Map.class);

                // 构建返回结果
                resultMap.put("success", true);
                resultMap.put("orderId", orderId);
                resultMap.put("outOrderNo", outOrderNo);
                resultMap.put("transactionId", order.getWxOrderId());
                resultMap.put("result", responseMap);

                return resultMap;

            } catch (com.github.binarywang.wxpay.exception.WxPayException e) {
                log.error("调用微信支付分账接口失败", e);
                throw new CommonException("调用微信支付分账接口失败: " + e.getMessage());
            }

        } catch (Exception e) {
            log.error("分账失败", e);
            resultMap.put("success", false);
            resultMap.put("errorMsg", e.getMessage());
            return resultMap;
        }
    }

    /**
     * 查询分账结果
     *
     * @param orderId 订单ID
     * @param outOrderNo 分账单号
     * @return 分账结果
     */
    @Override
    public Map<String, Object> queryProfitSharingResult(String orderId, String outOrderNo) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            // 获取订单信息
            BizTicketOrderIdParam param = new BizTicketOrderIdParam();
            param.setId(orderId);
            BizOrder order = bizTicketOrderService.detail(param);

            if (order == null) {
                throw new CommonException("订单不存在");
            }

            // 检查微信订单号是否存在
            if (StrUtil.isBlank(order.getWxOrderId())) {
                throw new CommonException("订单缺少微信支付订单号");
            }

            // 验证分账单号
            if (StrUtil.isBlank(outOrderNo)) {
                throw new CommonException("分账单号不能为空");
            }

            try {
                // 使用WxJava SDK查询分账结果
                ProfitSharingQueryRequest request =
                    new ProfitSharingQueryRequest();
                request.setTransactionId(order.getWxOrderId());
                request.setOutOrderNo(outOrderNo);
                // 设置mchId，防止空指针异常
                request.setMchId(wxPayService.getConfig().getMchId());

                ProfitSharingQueryResult result =
                    wxPayService.getProfitSharingService().profitSharingQuery(request);

                log.info("分账结果查询结果: {}", JSONUtil.toJsonStr(result));

                resultMap.put("success", true);
                resultMap.put("orderId", orderId);
                resultMap.put("outOrderNo", outOrderNo);
                resultMap.put("transactionId", order.getWxOrderId());
                resultMap.put("result", result);

            } catch (com.github.binarywang.wxpay.exception.WxPayException e) {
                log.error("查询微信支付分账结果失败", e);
                throw new CommonException("查询微信支付分账结果失败: " + e.getMessage());
            }

            return resultMap;
        } catch (Exception e) {
            log.error("查询分账结果失败", e);
            resultMap.put("success", false);
            resultMap.put("errorMsg", e.getMessage());
            return resultMap;
        }
    }

    /**
     * 创建认证头信息
     */
    private Map<String, String> createAuthHeaders() {
        Map<String, String> headers = new HashMap<>();
        try {
            // 使用wxPayService对象获取签名信息
            String token = wxPayService.getConfig().getApiV3Key();
            String nonce = String.valueOf(System.currentTimeMillis());
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String serialNo = wxPayService.getConfig().getCertSerialNo();

            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");
            headers.put("Authorization", "WECHATPAY2-SHA256-RSA2048 " +
                    "mchid=\"" + mchId + "\"," +
                    "nonce_str=\"" + nonce + "\"," +
                    "timestamp=\"" + timestamp + "\"," +
                    "serial_no=\"" + serialNo + "\"," +
                    "signature=\"***\""); // 实际使用中需要用SDK计算真实签名

            return headers;
        } catch (Exception e) {
            log.error("创建认证头信息失败", e);
            return headers;
        }
    }

    /**
     * 添加分账接收方
     *
     * @param openId 用户的OpenID
     * @param relationType 与分账方的关系类型
     * @return 添加结果
     */
    public boolean addProfitSharingReceiver(String openId, String relationType) {
        try {
            // 构建添加分账接收方的请求参数
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("appid", wxPayService.getConfig().getAppId());
            requestParams.put("type", "PERSONAL_OPENID");
            requestParams.put("account", openId);
            requestParams.put("relation_type", relationType);

            // 如果是自定义关系类型，需要设置自定义关系
            if ("CUSTOM".equals(relationType)) {
                requestParams.put("custom_relation", "分销佣金");
            }

            String requestJson = JSONUtil.toJsonStr(requestParams);
            log.info("添加分账接收方请求参数: {}", requestJson);

            // 调用微信支付V3 API添加分账接收方
            String url = "https://api.mch.weixin.qq.com/v3/profitsharing/receivers/add";
            String responseStr = wxPayService.postV3(url, requestJson);

            log.info("添加分账接收方结果: {}", responseStr);

            // 判断结果是否成功
            Map<String, Object> responseMap = JSONUtil.toBean(responseStr, Map.class);
            return responseMap != null && responseMap.containsKey("account");

        } catch (Exception e) {
            // 如果接收方已存在，可能会返回错误，但不影响后续分账
            log.error("添加分账接收方失败，可能该接收方已存在: {}", openId, e);
            return false;
        }
    }

    /**
     * 处理订单分账
     *
     * @param order 订单信息
     */
    private void handleOrderProfitSharing(BizOrder order) {
        log.info("开始处理订单分账，订单ID：{}", order.getId());

        try {
            // 创建分账订单
            BizFzOrder fzOrder = new BizFzOrder();
            fzOrder.setOrderId(order.getId());
            fzOrder.setTicketId(order.getTicketId());
            fzOrder.setPrice(order.getPrice());
            fzOrder.setOrderOverTime(order.getUpdateTime());

            // 查询门票信息
            Ticket ticket = ticketService.getById(order.getTicketId());
            if (ticket == null) {
                throw new CommonException("门票信息不存在");
            }

            // 总分账金额
            BigDecimal totalAmount = order.getPrice();
            BigDecimal totalShareAmount = BigDecimal.ZERO;

            // 创建分账接收方列表
            List<Map<String, Object>> receivers = new ArrayList<>();
            List<BizFzOrderDetail> fzDetails = new ArrayList<>();

            // 1. 处理旅行社分账 - 根据票记录表中的分佣金额和分佣ID
//            if (ticket.getCommissionLxs() != null && ticket.getCommissionLxs().compareTo(BigDecimal.ZERO) > 0
//                    && StrUtil.isNotBlank(ticket.getUseridLxs())) {
//                try {
//                    // 计算旅行社分账金额 - 按比例计算
//                    BigDecimal lxsShare = ticket.getCommissionLxs();
//
//                    // 累加分账金额
//                    totalShareAmount = totalShareAmount.add(lxsShare);
//
//                    // 添加旅行社分账明细
//                    BizFzOrderDetail lxsDetail = new BizFzOrderDetail();
//                    lxsDetail.setOrderId(order.getId());
//                    lxsDetail.setTicketId(order.getTicketId());
//                    lxsDetail.setMoney(lxsShare);
//                    lxsDetail.setUserId(ticket.getUseridLxs());
//                    fzDetails.add(lxsDetail);
//
//                    // 获取旅行社OpenID
//                    String lxsOpenId = sysOrgService.getById(ticket.getUseridLxs()).getOpenId();
//                    if (StrUtil.isBlank(lxsOpenId)) {
//                        log.error("旅行社OpenID为空，无法进行分账, ID: {}", ticket.getUseridLxs());
//                    } else {
//                        // 先添加为分账接收方
//                        addProfitSharingReceiver(lxsOpenId, "PARTNER");
//
//                        // 添加旅行社分账接收方
//                        Map<String, Object> lxsReceiver = new HashMap<>();
//                        lxsReceiver.put("type", "PERSONAL_OPENID"); // 个人OPENID类型
//                        lxsReceiver.put("account", lxsOpenId);
//                        lxsReceiver.put("amount", lxsShare.multiply(new BigDecimal("100")).intValue());
//                        lxsReceiver.put("description", "旅行社分佣");
//                        receivers.add(lxsReceiver);
//
//                        log.info("旅行社分账金额：{}，接收方ID：{}", lxsShare, ticket.getUseridLxs());
//                    }
//                } catch (Exception e) {
//                    log.error("处理旅行社分账时发生异常", e);
//                }
//            }

            // 2. 处理代理人分账 - 根据订单表中的邀请人ID
            if (StrUtil.isNotBlank(order.getInvitationUserId())) {
                try {
                    // 查询代理人信息
                    BizFzUser agent = bizFzUserService.getById(order.getInvitationUserId());
                    if (agent != null) {
                        // 计算代理人分账金额 - 按代理人的分账类型计算
                        BigDecimal agentShare = calculateAgentShare(agent, ticket, 2, totalAmount, order.getTicketCount());
                        if (agentShare.compareTo(BigDecimal.ZERO) > 0) {
                            // 累加分账金额
                            totalShareAmount = totalShareAmount.add(agentShare);

                            // 添加代理人分账明细
                            BizFzOrderDetail agentDetail = new BizFzOrderDetail();
                            agentDetail.setOrderId(order.getId());
                            agentDetail.setTicketId(order.getTicketId());
                            agentDetail.setMoney(agentShare);
                            agentDetail.setUserId(agent.getId());
                            fzDetails.add(agentDetail);

                            // 检查代理人OpenID
                            if (StrUtil.isBlank(agent.getOpenId())) {
                                log.error("代理人OpenID为空，无法进行分账, ID: {}", agent.getId());
                            } else {
                                // 先添加为分账接收方
                                addProfitSharingReceiver(agent.getOpenId(), "DISTRIBUTOR");

                                // 添加代理人分账接收方
                                Map<String, Object> agentReceiver = new HashMap<>();
                                agentReceiver.put("type", "PERSONAL_OPENID"); // 个人OPENID类型
                                agentReceiver.put("account", agent.getOpenId());
                                agentReceiver.put("amount", agentShare.multiply(new BigDecimal("100")).intValue());
                                agentReceiver.put("description", "代理人分佣");
                                receivers.add(agentReceiver);

                                log.info("代理人分账金额：{}，接收方ID：{}", agentShare, agent.getId());
                            }

                            // 检查是否有上级代理人
                            if (!agent.getParentId().equals("0")) {
                                try {
                                    BizFzUser parentAgent = bizFzUserService.getById(agent.getParentId());
                                    if (parentAgent != null) {
                                        // 计算上级代理人分账金额
                                        BigDecimal parentShare = calculateAgentShare(parentAgent, ticket, 1, totalAmount, order.getTicketCount());
                                        if (parentShare.compareTo(BigDecimal.ZERO) > 0) {
                                            // 累加分账金额
                                            totalShareAmount = totalShareAmount.add(parentShare);

                                            // 添加上级代理人分账明细
                                            BizFzOrderDetail parentDetail = new BizFzOrderDetail();
                                            parentDetail.setOrderId(order.getId());
                                            parentDetail.setTicketId(order.getTicketId());
                                            parentDetail.setMoney(parentShare);
                                            parentDetail.setUserId(parentAgent.getId());
                                            fzDetails.add(parentDetail);

                                            // 检查上级代理人OpenID
                                            if (StrUtil.isBlank(parentAgent.getOpenId())) {
                                                log.error("上级代理人OpenID为空，无法进行分账, ID: {}", parentAgent.getId());
                                            } else {
                                                // 先添加为分账接收方
                                                addProfitSharingReceiver(parentAgent.getOpenId(), "DISTRIBUTOR");

                                                // 添加上级代理人分账接收方
                                                Map<String, Object> parentReceiver = new HashMap<>();
                                                parentReceiver.put("type", "PERSONAL_OPENID"); // 个人OPENID类型
                                                parentReceiver.put("account", parentAgent.getOpenId());
                                                parentReceiver.put("amount", parentShare.multiply(new BigDecimal("100")).intValue());
                                                parentReceiver.put("description", "上级代理人分佣");
                                                receivers.add(parentReceiver);

                                                log.info("上级代理人分账金额：{}，接收方ID：{}", parentShare, parentAgent.getId());
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    log.error("处理上级代理人分账时发生异常", e);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("处理代理人分账时发生异常", e);
                }
            }

            // 3. 处理总代理分账 - 只要getCommissionOneDlr或getCommissionTwoDlr有一个大于0
            if ((ticket.getCommissionOneDlr() != null && ticket.getCommissionOneDlr().compareTo(BigDecimal.ZERO) > 0)
                || (ticket.getCommissionTwoDlr() != null && ticket.getCommissionTwoDlr().compareTo(BigDecimal.ZERO) > 0)) {
                try {
//                    BigDecimal zdlShare = new BigDecimal("2").multiply(new BigDecimal(order.getTicketCount()));
                    // 使用原旅行社分账   用来记录总代理分账金额
                    BigDecimal zdlShare = ticket.getCommissionLxs().multiply(new BigDecimal(order.getTicketCount()));
                    // 累加分账金额
                    totalShareAmount = totalShareAmount.add(zdlShare);

                    // 添加总代理分账明细（如需保存明细，可仿照上面代理人明细添加）
                     BizFzOrderDetail zdlDetail = new BizFzOrderDetail();
                     zdlDetail.setOrderId(order.getId());
                     zdlDetail.setTicketId(order.getTicketId());
                     zdlDetail.setMoney(zdlShare);
                     zdlDetail.setUserId("1926546004783718402"); // 如有总代理ID可填写
                     fzDetails.add(zdlDetail);

                    // 添加总代理分账接收方
                    Map<String, Object> zdlReceiver = new HashMap<>();
                    zdlReceiver.put("type", "PERSONAL_OPENID");
                    zdlReceiver.put("account", "oxQAH7M-TeeiC7FLT_VtA7DkQBC8");
                    zdlReceiver.put("amount", zdlShare.multiply(new BigDecimal("100")).intValue());
//                    if ("1933718540759887873".equals(ticket.getId())) {
//                        // 特殊处理，包船2800海钓，分账100元RMB
//                        zdlReceiver.put("amount", new BigDecimal("10000").multiply(new BigDecimal(order.getTicketCount())).intValue());
//                    }
//                    if ("457820250702110435684".equals(order.getId())) {
//                        // 特殊处理，补偿未正常配置分账订单，分账+40
//                        zdlReceiver.put("amount", (zdlShare.add(new BigDecimal("40"))).multiply(new BigDecimal("100")).intValue());
//                    }
                    zdlReceiver.put("description", "总代理分账");
                    receivers.add(zdlReceiver);

                    log.info("总代理分账金额：{}，接收方account：{}", zdlShare, "oxQAH7M-TeeiC7FLT_VtA7DkQBC8");
                } catch (Exception e) {
                    log.error("处理总代理分账时发生异常", e);
                }
            }

            // 计算平台分账金额（剩余金额）
            BigDecimal platformShare = totalAmount.subtract(totalShareAmount);

            // 设置分账订单信息
            fzOrder.setMoney(totalShareAmount);
            fzOrder.setMyMoney(platformShare);

            // 保存分账订单
            bizTicketOrderService.saveFzOrder(fzOrder);

            // 保存分账明细
            if (!fzDetails.isEmpty()) {
                // 设置分账订单ID
                for (BizFzOrderDetail detail : fzDetails) {
                    detail.setFzOrderId(fzOrder.getId());
                }
                bizTicketOrderService.saveFzOrderDetails(fzDetails);
            }

            // 调用分账接口
            if (!receivers.isEmpty()) {

                Map<String, Object> result = profitSharing(order.getId(), fzOrder.getId(), receivers);
                log.info("订单{}分账结果：{}", order.getId(), result);

                // 更新分账订单记录，保存分账单号和分账结果
                if ((Boolean) result.get("success")) {
                    // 获取分账单号和其他信息
                    String outOrderNo = (String) result.get("outOrderNo");

                    // 更新分账订单信息
                    fzOrder.setOutOrderNo(outOrderNo);
                    fzOrder.setWxProfitSharingResult(JSONUtil.toJsonStr(result.get("result")));
                    bizTicketOrderService.updateFzOrder(fzOrder);

                    // 是否需要自动完结分账，视业务需求决定
                    // 如果确定只有一次分账，可以在分账成功后立即完结
                    // 如果可能会有多次分账，则应该在最后一次分账后再完结
//                    try {
//                        log.info("延迟3秒后执行完结分账");
//                        Thread.sleep(3000);
//                        // 调用完结分账
//                        Map<String, Object> finishResult = finishProfitSharing(order.getId());
//                        log.info("订单{}完结分账结果：{}", order.getId(), finishResult);
//                    } catch (Exception e) {
//                        log.error("完结分账异常", e);
//                    }
                }
            } else {
                log.info("订单{}没有分账接收方，跳过分账操作", order.getId());
            }
        } catch (Exception e) {
            log.error("处理订单分账异常，订单ID：{}", order.getId(), e);
        }
    }

    /**
     * 计算代理人分账金额
     *
     * @param agent 代理人信息
     * @param ticket 门票信息
     * @param jb 级别：1-一级代理人，2-二级代理人
     * @param totalAmount 订单总金额
     * @return 分账金额
     */
    private BigDecimal calculateAgentShare(BizFzUser agent, Ticket ticket, int jb, BigDecimal totalAmount, int ticketCount) {
        // 2025-05-14 注释原分账算法，改为使用票务信息中的一二级分佣金额进行分账
        // if (agent == null || agent.getFzValue() == null) {
        //     return BigDecimal.ZERO;
        // }

        // // 根据分账类型计算分账金额
        // if ("GDJE".equals(agent.getFzType())) {
        //     // 固定金额
        //     return agent.getFzValue();
        // } else if ("BFB".equals(agent.getFzType())) {
        //     // 按百分比计算
        //     return totalAmount.multiply(agent.getFzValue())
        //             .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        // }

        // 票务信息中的一二级分佣金额，jb=2为默认二级分佣，需要判断如果无上级的情况需要合并一二级分佣
        if (jb == 1 && ticket.getCommissionOneDlr()!= null && ticket.getCommissionOneDlr().compareTo(BigDecimal.ZERO) > 0) {
            return ticket.getCommissionOneDlr().multiply(new BigDecimal(ticketCount));
        }
        if (jb == 2 && ticket.getCommissionTwoDlr()!= null && ticket.getCommissionTwoDlr().compareTo(BigDecimal.ZERO) > 0) {
            if (agent.getParentId().equals("0") && ticket.getCommissionOneDlr()!= null && ticket.getCommissionOneDlr().compareTo(BigDecimal.ZERO) > 0) {
                return (ticket.getCommissionTwoDlr().add(ticket.getCommissionOneDlr())).multiply(new BigDecimal(ticketCount));
            }
            return ticket.getCommissionTwoDlr().multiply(new BigDecimal(ticketCount));
        }

        return BigDecimal.ZERO;
    }

    /**
     * 定时任务：每天零点执行，处理已支付订单状态更新为已完成
     * 处理条件：
     * 1. 已支付的订单
     * 2. 如果没有预约时间，则判断订单创建时间是否超过一天
     * 3. 如果有预约时间，则判断是否超过预约时间一天
     */
    @Scheduled(cron = "0 0 9 * * ?") // 每天00:00:00执行
    public void updateOrderStatusToCompleted() {
        log.info("开始执行订单状态自动更新为已完成的定时任务");

        try {
            // 当前时间
            Date now = new Date();
            // 计算一天前的时间
            Date oneDayAgo = DateUtil.offsetDay(now, -1);

            // 查询所有符合条件的已支付订单
            LambdaQueryWrapper<BizOrder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BizOrder::getStatus, "已支付");

            List<BizOrder> paidOrders = bizTicketOrderService.list(queryWrapper);

            if (paidOrders.isEmpty()) {
                log.info("没有需要更新的已支付订单");
                return;
            }

            int updatedCount = 0;
            for (BizOrder order : paidOrders) {
                try {
                    // 获取分布式锁
                    RLock lock = redissonClient.getLock("lock:order:complete:" + order.getId());
                    if (lock.tryLock()) {
                        try {
                            boolean shouldComplete = false;

                            // 再次查询确认订单状态
                            BizOrder currentOrder = bizTicketOrderService.getById(order.getId());
                            if (currentOrder == null || !"已支付".equals(currentOrder.getStatus())) {
                                continue;
                            }

                            // 判断是否需要更新为已完成
                            if (currentOrder.getReservationTime() != null) {
                                // 有预约时间，判断是否超过预约时间一天
                                Date oneDayAfterReservation = DateUtil.offsetDay(currentOrder.getReservationTime(), 1);
                                shouldComplete = now.after(oneDayAfterReservation);
                            //} else {
                            //    // 没有预约时间，判断是否超过创建时间一天
                            //    shouldComplete = currentOrder.getCreateTime() != null &&
                            //            oneDayAgo.after(currentOrder.getCreateTime());
                            }

                            if (shouldComplete) {
                                // 更新订单状态为已完成
                                currentOrder.setStatus("已完成");
                                bizTicketOrderService.updateById(currentOrder);
                                updatedCount++;
                                log.info("订单状态已更新为已完成，订单ID: {}", currentOrder.getId());

                                // 处理订单分账
                                handleOrderProfitSharing(currentOrder);
                            }
                        } finally {
                            lock.unlock();
                        }
                    }
                } catch (Exception e) {
                    log.error("更新订单状态失败，订单ID: {}", order.getId(), e);
                }
            }

            log.info("订单状态自动更新定时任务完成，共更新{}个订单状态为已完成", updatedCount);
        } catch (Exception e) {
            log.error("执行订单状态自动更新定时任务异常", e);
        }
    }

    /**
     * 完结分账
     *
     * @param orderId 订单ID
     * @return 完结分账结果
     */
    public Map<String, Object> finishProfitSharing(String orderId) {
        return null;
    }
}
